package com.zeros.usercenter.ui.activity

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.util.Log
import com.bigkoo.alertview.AlertView
import com.bigkoo.alertview.OnItemClickListener
import com.jph.takephoto.app.TakePhoto
import com.jph.takephoto.app.TakePhotoImpl
import com.jph.takephoto.compress.CompressConfig
import com.jph.takephoto.model.InvokeParam
import com.jph.takephoto.model.TContextWrap
import com.jph.takephoto.model.TResult
import com.jph.takephoto.permission.InvokeListener
import com.zeros.baselibrary.ext.onClick
import com.zeros.baselibrary.ui.activity.BaseMvpActivity
import com.zeros.baselibrary.utils.DateUtils
import com.zeros.usercenter.R
import com.zeros.usercenter.presenter.UserInfoPresenter
import kotlinx.android.synthetic.main.activity_user_info.*
import java.io.File
import com.jph.takephoto.permission.PermissionManager
import com.jph.takephoto.permission.PermissionManager.TPermissionType
import android.Manifest.permission
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.widget.Toast
import com.jph.takephoto.permission.TakePhotoInvocationHandler
import com.qiniu.android.http.ResponseInfo
import com.qiniu.android.storage.UpCompletionHandler
import com.qiniu.android.storage.UploadManager
import com.zeros.baselibrary.common.BaseConstant
import com.zeros.baselibrary.utils.AppPrefsUtils
import com.zeros.baselibrary.utils.GlideUtils
import com.zeros.provider.common.ProviderConstant
import com.zeros.usercenter.R.id.mUserIconView
import com.zeros.usercenter.data.protocol.UserInfo
import com.zeros.usercenter.presenter.view.UserInfoView
import com.zeros.usercenter.utils.UserPrefsUtils
import org.jetbrains.anko.toast
import org.json.JSONObject


class UserInfoActivity : BaseMvpActivity<UserInfoPresenter>(),
        TakePhoto.TakeResultListener, InvokeListener, UserInfoView {

    //访问camera与ALbum的
    private lateinit var mTakePhoto: TakePhoto
    private var invokeParam: InvokeParam? = null
    private lateinit var mTempFile: File

    //七牛上传
    private val mUploadManage: UploadManager by lazy { UploadManager() }
    private var mLocalFileUrl: String? = null          //选取的图片地址
    private var mRemoteFileUrl: String? = null      //拼接完整七牛云地址

    //布局view
    private var mUserIcon: String? = null
    private var mUserName: String? = null
    private var mUserMobile: String? = null
    private var mUserGender: String? = null
    private var mUserSign: String? = null;


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_user_info)

        mPresenter = UserInfoPresenter()    //必须初始画
        mPresenter.mView = this

        mTakePhoto = getTakePhoto()    //初始化--TakePhotoImpl(this, this)[这种要自己写权限]
        mTakePhoto.onCreate(savedInstanceState)

        initView()
        initData()
    }

    /*--这种方式可以判断权限--*/
    private fun getTakePhoto(): TakePhoto {
//        if (mTakePhoto == null) {
        //在6.0 与 7.0中必须实现InvokeListener，即实现权限判断
        mTakePhoto = TakePhotoInvocationHandler.of(this)
                .bind(TakePhotoImpl(this, this)) as TakePhoto

//        }
        return mTakePhoto
    }

    fun initView() {
        //头像
        mUserIconView.onClick {
            showAlertView()
        }

        //保存按钮--(编辑资料)
        mHeaderBar.getRightView().onClick {
            mPresenter.editUser(mRemoteFileUrl!!,
                    mUserNameEt.text?.toString() ?: "",
                    if (mGenderMaleRb.isChecked) "0" else "1",
                    mUserSignEt.text?.toString() ?: "")
        }
    }

    /*-初始数据就是设置布局-*/
    private fun initData() {
        //从存储中取出来
        mUserIcon = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_ICON)
        mUserName = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_NAME)
        mUserMobile = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_MOBILE)
        mUserGender = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_GENDER)
        mUserSign = AppPrefsUtils.getString(ProviderConstant.KEY_SP_USER_SIGN)

        //在编辑资料时，若没有修改头像则是最初的头像
        mRemoteFileUrl = mUserIcon

        //如果图片地址不为空-则加载头像
        if (mUserIcon != "") {
            GlideUtils.loadUrlImage(this, mUserIcon!!, mUserIconIv)
        }
        mUserNameEt.setText(mUserName)  //昵称
        mUserMobileTv.text = mUserMobile    //手机

        if (mUserGender == "0") {
            mGenderMaleRb.isChecked = true
        } else {
            mGenderFemaleRb.isChecked = true
        }
        mUserSignEt.setText(mUserSign)  //签名
    }

    /*- 弹出选择框，默认实现，可根据实际情况，自行修改-*/
    private fun showAlertView() {
        AlertView("选择图片", "", "取消", null,
                arrayOf("拍照", "相册"), this, AlertView.Style.ActionSheet,
                OnItemClickListener { o, position ->

                    //没次都要对图片进行压缩
                    mTakePhoto.onEnableCompress(CompressConfig.ofDefaultConfig(), false)

                    when (position) {
                        0 -> {
//                            setPerimission()
                            createTempFile()
                            mTakePhoto.onPickFromCapture(Uri.fromFile(mTempFile))
                        }
                        1 -> mTakePhoto.onPickFromGallery()
                    }
                }).show()
    }

    private fun setPerimission() {
        createTempFile()
        if (Build.VERSION.SDK_INT >= 23) {
            val checkCamera = ContextCompat.checkSelfPermission(this@UserInfoActivity, Manifest.permission.CAMERA)
            if (checkCamera != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this@UserInfoActivity, arrayOf(Manifest.permission.CAMERA), 222)
                return
            } else {
                mTakePhoto.onPickFromCapture(Uri.fromFile(mTempFile))
            }
        } else {
            mTakePhoto.onPickFromCapture(Uri.fromFile(mTempFile))
        }
    }

    //获取URI--新建临时文件
    fun createTempFile() {
        val tempFileName = "${DateUtils.curTime}.png"
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            this.mTempFile = File(Environment.getExternalStorageDirectory(), tempFileName)
            return
        }
        this.mTempFile = File(filesDir, tempFileName)
    }

    /*----------UserInfoView回调---------------*/
    override fun onGetUploadTokenResult(result: String) {
        mUploadManage.put(mTempFile, null, result, object : UpCompletionHandler {
            override fun complete(key: String?, info: ResponseInfo?, response: JSONObject?) {
                //完整URL地址-response.get("hash")-图片位置
                mRemoteFileUrl = BaseConstant.IMAGE_SERVER_ADDRESS + response!!.get("hash")

                GlideUtils.loadUrlImage(this@UserInfoActivity, mRemoteFileUrl!!, mUserIconIv)
            }
        }, null)
    }

    override fun onEditUserResult(result: UserInfo) {
        toast("修改成功")
        //保存最新的
        UserPrefsUtils.putUserInfo(result)
    }

    /*----------takePhoto返回接口--------------*/
    override fun takeSuccess(result: TResult?) {
        Log.e("UserActivity:", result?.image?.originalPath)   //原始地址
        Log.e("UserActivity-2:", result?.image?.compressPath)   //压缩地址

        mLocalFileUrl = result?.image?.compressPath

        //从自己服务器拿七牛上传凭证
        mPresenter.getUploadToken()
    }

    override fun takeCancel() {
    }

    override fun takeFail(result: TResult?, msg: String?) {
        Log.e("takePhoto", msg)
    }

    /*---------其他activity结果返回--------------*/
    //Intent的返回
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mTakePhoto.onActivityResult(requestCode, resultCode, data)
    }

    //权限的返回
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //以下代码为处理Android6.0、7.0动态权限所需
        val type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this)

//        when (requestCode) {
//            222 -> {
//                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    // Permission Granted
//                    mTakePhoto.onPickFromCapture(Uri.fromFile(mTempFile))
//                } else {
//                    // Permission Denied
//                    toast("很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。")
//                }
//            }
//        }

    }

    /*-判断权限-*/
    override fun invoke(invokeParam: InvokeParam): TPermissionType {
        val type: TPermissionType = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.method)
        if (TPermissionType.WAIT == type) {
            this.invokeParam = invokeParam
        }
        return type
    }


}
